package projet.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import projet.entity.Course;
import projet.entity.Location;
import projet.service.HomeService;

/**
 * Servlet implementation class HomeServlet
 */
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private HomeService homeService = new HomeService();
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public HomeServlet() {
		super();
		// Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			List<Location> locations = homeService.getLocations();
			List<Course> courses = null;
			
			String keywordStr = request.getParameter("keyword");
			String locationIdStr = request.getParameter("locationId");
			String dateStr = request.getParameter("date");
			if (keywordStr == null && locationIdStr == null && dateStr == null) {
				courses = homeService.getCourses();
			} else {
				String keyword = null;
				Long locationId = null;
				Date date = null;
				if (keywordStr != null && !keywordStr.isEmpty()) {
					keyword = keywordStr;
				}
				if (locationIdStr != null && !locationIdStr.isEmpty()) {
					locationId = Long.parseLong(locationIdStr);
				}
				if (dateStr != null && !dateStr.isEmpty()) {
					SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
					date = sdf.parse(dateStr);
				}
				courses = homeService.getCoursesByCriteria(keyword, locationId, date);
			}
			
			request.setAttribute("courses", courses);
			request.setAttribute("locations", locations);
			request.setAttribute("keyword", keywordStr);
			request.setAttribute("locationId", locationIdStr);
			request.setAttribute("date", dateStr);
			RequestDispatcher dispatcher = request.getRequestDispatcher("home.jsp");
			dispatcher.forward(request, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
